<template>
  <div>
    <MyTable :arr="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{ item }">
        <td>{{ item.id }}</td>
        <td>{{ item.goods_name }}</td>
        <td>{{ item.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="item.inputVisible"
            v-foucs
            @blur="item.inputVisible = false"
            v-model="item.inputValue"
            @keydown.esc="item.inputValue = ''"
            @keydown.enter="enterFn(item)"
          />
          <button 
          v-else 
          style="display: block;" 
          class="btn btn-primary btn-sm add-tag"
          @click="item.inputVisible = true"
          >+Tag</button>
          <span
            v-for="(i, index) in item.tags"
            :key="index"
            class="badge badge-warning"
            >{{ i }}
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delBtn(item.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from './MyTable'
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [], // 所有数据
    }
  },
  created() {
    this.$axios({
      url: '/api/goods',
    }).then((res) => {
      // console.log(res)
      this.list = res.data.data
    })
  },
  methods: {
    delBtn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    enterFn(item) {
      // 判断,为空就return
      if(item.inputValue.trim() === '') alert('输入内容不能为空')
      // 不为空就push到数组中
      item.tags.push(item.inputValue)
      item.inputValue = ''
      item.inputVisible = false
    }
  },
  directives:{
    foucs:{
      inserted(el) {
        el.focus()
      }
    },
  }
}
</script>

<style lang="less" scoped>
.badge {
  margin-right: 8px;
}
</style>
